//
//  RHMePlantInfoBarChartView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/7.
//

#import "RHMePlantInfoBarChartView.h"
#import "DeviceChartItemView.h"
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"
#import "QMUILabel+LHAdd.h"
#import "RHBarChartMarkerView.h"
#import "RHLeftAxisFormatter.h"
#import "RHRightAxisFormatter.h"
@interface RHMePlantInfoBarChartView()
<ChartAxisValueFormatter,ChartValueFormatter,ChartViewDelegate>
@property (nonatomic ,copy) NSArray *colorList;
//前一天
@property (nonatomic ,strong) QMUIButton *l_btn;
//后一天
@property (nonatomic ,strong) QMUIButton *r_btn;
//日期
@property (nonatomic ,strong) QMUIButton *timeBtn;

//左边Y轴单位
@property (nonatomic, strong) QMUILabel *leftUnitLab;
//右边Y轴单位
@property (nonatomic, strong) QMUILabel *rightUnitLab;

//气泡
//@property (nonatomic, strong) PEMaskView *maskView;

@property (nonatomic, strong) RHBarChartMarkerView *markerView;
/// 图表
@property (nonatomic, strong) BarChartView *barChartView;
//年,月,日
@property (nonatomic ,assign) NSInteger type;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) UIView *scrollBgView;

@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) NSMutableArray *itemsArray;

@property (nonatomic, strong) NSMutableArray *unitArr;

@property (nonatomic, assign) BOOL isLandscape;//是否横屏

@end
@implementation RHMePlantInfoBarChartView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type isLandscape:(BOOL)isLandscape{
    self = [super initWithFrame:frame];
    if (self) {
        self.colorList = @[@"#FFCE00",@"#678EF2",@"#10E2FF",@"#B36DFA",@"#98D767",@"FB6085",@"8956F8"];
        self.type = type;
        _isLandscape = isLandscape;
        [self setupUI];
        
    }
    return self;
}

- (void)setColorList:(NSArray*)colorList
{
    _colorList = colorList;
    [self.itemsArray enumerateObjectsUsingBlock:^(DeviceChartItemView*  _Nonnull itemView, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *colorHexStr = [colorList safeObjectAtIndex:idx % colorList.count];
        [itemView.markLab.layer setBorderColor:FontColor(colorHexStr).CGColor];
    }];
}

- (void)setChartModel:(DevChartModel *)chartModel{
   
    _chartModel = chartModel;
    self.selectIndex = _chartModel.timeType;
    [self.markerView updateModel:chartModel colors:self.colorList];
    [self setChartData];
    NSString *timeStr;
    if (_chartModel.timeType == TimeType_Day) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString *dateTime = [formatter stringFromDate:date];
        timeStr = dateTime;
        [_r_btn setEnabled:[date isToday]?NO:YES];
    }else if (_chartModel.timeType == TimeType_Month) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%02ld-%02ld",[date year],[date month]];
        [_r_btn setEnabled:[[NSDate date] monthsLaterThan:date]?YES:NO];
    }else if (_chartModel.timeType == TimeType_Year){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%ld",[date year]];
        [_r_btn setEnabled:[[NSDate date] yearsLaterThan:date]?YES:NO];
    }else{
        timeStr = @"";
    }

    [self.timeBtn setTitle:ValidStr(timeStr)?timeStr:@"" forState:UIControlStateNormal];
    
    //移除,重新布局
    [self.itemsArray enumerateObjectsUsingBlock:^(DeviceChartItemView*  _Nonnull itemView, NSUInteger idx, BOOL * _Nonnull stop) {
        [itemView removeFromSuperview];
    }];
    
    //屏幕宽度
    CGFloat screenWidth = _isLandscape?MAX(kUI_WINDOW_W-kSafe_top, kUI_WINDOW_H):MIN(kUI_WINDOW_W, kUI_WINDOW_H);
    //总宽度
    __block CGFloat width = screenWidth - 30 - 10;
    NSLog(@"------>总宽度:%f",width);
    __block CGFloat total_width = 15;
    __block DeviceChartItemView *lastView;
    __block CGFloat scrollContentWidth = 0;//计算完后居中
     
 
    kWeakSelf;
    [self.itemsArray enumerateObjectsUsingBlock:^(DeviceChartItemView  *_Nonnull itemView, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat item_width = 0;
        DeviceChartFieldModel *model;
        if (idx<weakSelf.chartModel.selectArray.count) {
            [weakSelf.scrollBgView addSubview:itemView];
            model = weakSelf.chartModel.selectArray[idx];
            NSArray *lineColors = weakSelf.colorList;
            if (weakSelf.chartModel.colorArr.count>0) {
                lineColors = weakSelf.chartModel.colorArr;
            }
            model.colorStr = lineColors[idx];
            [itemView setModel:model];
            [itemView.markLab.layer setBorderColor:FontColor(model.colorStr).CGColor];
            item_width = [itemView.conentLab.text getStringWidthFont:itemView.conentLab.font limitHeight:20] + 25;
            
            //超过总宽度,换行
            if((total_width+item_width+15) > width){
                NSLog(@"------->换行:%ld",idx);
                total_width = item_width + 15;
                [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(item_width);
                    make.left.mas_offset(15);
                    make.top.equalTo(lastView.mas_bottom).offset(15);
                }];
                //清除上一个参考view,重左边开始而已
                lastView = nil;
            }else{
                if (lastView) {
                    NSLog(@"------->不用换行:%ld",idx);
                    [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(item_width);
                        make.left.equalTo(lastView.mas_right).offset(15);
                        make.top.equalTo(lastView);
                    }];
                }else{
                    NSLog(@"------->第一个:%ld",idx);
                    [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(item_width);
                        make.left.mas_offset(15);
                        make.top.mas_offset(15);
                    }];
                }
                
                //每行的宽度
                total_width = total_width+item_width+15;
            }
            //每行的最大宽度
            scrollContentWidth = MAX(scrollContentWidth, total_width);
            lastView = itemView;
        }

        itemView.selectBlock = ^BOOL(DeviceChartFieldModel * _Nonnull model) {
            model.isShowLine = !model.isShowLine;
            [weakSelf.chartModel updateyAxisArray];
            [weakSelf setChartData];
            return YES;
        };
    }];

    //封底
    if (lastView) {
        [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_offset(-15);
        }];
    }
    
    //居中
    [self.scrollBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.barChartView.mas_bottom).offset(5);
        make.width.offset(scrollContentWidth);
        make.centerX.offset(0);
        make.bottom.mas_offset(0);
        
    }];
}

-(void)setChartData
{
    [self.barChartView clear];
    self.leftUnitLab.hidden = YES;
   
    [self.unitArr removeAllObjects];
    kWeakSelf;
    __block CGFloat left_y_max = 0;
    __block CGFloat right_y_max = 0;
    __block CGFloat left_y_min = 0;
    __block CGFloat right_y_min = 0;
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
  
    
    __block NSInteger dataSetCount = 0;
    [self.chartModel.selectArray enumerateObjectsUsingBlock:^(DeviceChartFieldModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        if(model.dataArray.count == 0)return;
        if(model.isShowLine){
            dataSetCount++;
            NSArray *lineColors = weakSelf.colorList;
            if (weakSelf.chartModel.colorArr.count>0) {
                lineColors = weakSelf.chartModel.colorArr;
            }
            BarChartDataSet *set = [weakSelf createDataSetWithModel:model linecolor:[lineColors safeObjectAtIndex:idx]];
            //单位
            if(![weakSelf.unitArr containsObject:model.unitName]){
                [weakSelf.unitArr addObject:ValidNullDataToString(model.unitName, @"--")];
            }
            //数据对应 左边Y轴 还是 右边Y轴
            if(weakSelf.unitArr.count<2){
                set.axisDependency = AxisDependencyLeft;
                left_y_max = MAX(model.y_max, left_y_max);
                left_y_min = MIN(model.y_min, left_y_min);
                weakSelf.leftUnitLab.text = model.unitName;
                weakSelf.leftUnitLab.hidden = NO;
            }else{
                //两个单位
                if([model.unitName isEqualToString:weakSelf.unitArr[0]]){
                    set.axisDependency = AxisDependencyLeft;
                    left_y_max = MAX(model.y_max, left_y_max);
                    left_y_min = MIN(model.y_min, left_y_min);
                }else{
                    set.axisDependency = AxisDependencyRight;
                    right_y_max = MAX(model.y_max, right_y_max);
                    right_y_min = MIN(model.y_min, right_y_min);
                    weakSelf.rightUnitLab.text = model.unitName;
                    weakSelf.rightUnitLab.hidden = NO;
                }
                
                weakSelf.barChartView.rightAxis.enabled = YES;
            }
            
            [dataSets addObject:set];
            
        }
        
    }];
    //没有数据的时候也展示
    if(left_y_max == 0)
    {
        left_y_max = 10;
    }
    if(right_y_max == 0){
        right_y_max = 10;
    }
    self.barChartView.leftAxis.axisMaximum = left_y_max;
    self.barChartView.leftAxis.axisMinimum = left_y_min;
    self.barChartView.rightAxis.axisMaximum = right_y_max;
    self.barChartView.rightAxis.axisMinimum = right_y_min;
   
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    if (dataSetCount == 0) {
        dataSetCount = 1;
    }
    //每组的间距
    float groupSpace = 0.2;
    //每条柱子之间的间距
    float barSpace = 0.1;
    //每个柱子的宽度
    float barWidth = (1 - groupSpace)/dataSetCount - barSpace;
    
    data.barWidth = barWidth;
  
    // 设置X轴数据
    _barChartView.data = data;
//    CGFloat granularity = (barWidth + barSpace) * dataSets.count + groupSpace;
//    NSLog(@"---->每组的间隔:%f",granularity);
//    //（barWidth + barSpace）* 组内个数 + groupSpace = 每个"组"的间隔 granularity,这个关系对齐问题
//    _barChartView.xAxis.granularity = granularity;
    
    //*****注意:这里 -0.5 是为了使柱子和下面的X坐标值对齐,如果修改了,气泡图 RHBarChartMarkerView 里绘制以及计算方法中有关entry.x计算index时要同时修改(+0.5),不然点击柱子时气泡中的数据会不对(减少了0.5)
    _barChartView.xAxis.axisMaximum = -0.5 + [data groupWidthWithGroupSpace:groupSpace barSpace: barSpace] * self.chartModel.xTitlesArray.count;
    _barChartView.xAxis.axisMinimum = -0.5;
    [data groupBarsFromX:-0.5 groupSpace: groupSpace barSpace: barSpace];
    
    
    //设置x轴标签显示数量
    NSInteger labelCount = 8;
    if(self.chartModel.timeType == TimeType_Day){
//        [_barChartView setVisibleXRangeMaximum:24];
        if (self.isLandscape) {
            labelCount = 12;
        }
    }
    if(self.chartModel.timeType == TimeType_Month){
//        [_barChartView setVisibleXRangeMaximum:31];
        if (self.isLandscape) {
            labelCount = 12;
        }
    }
    if(self.chartModel.timeType == TimeType_Year){
//        [_barChartView setVisibleXRangeMaximum:12];
        labelCount = 12;
    }
    [self.barChartView.xAxis setLabelCount:labelCount force:NO];//设置x轴显示的个数
//    [_barChartView setVisibleXRangeMaximum:8];
    
    //这里可以调用一个加载动画即1s出来一个绘制点
//    [self.lineChartView animateWithXAxisDuration:0.2f];
   
    //柱子圆角  https://www.jianshu.com/p/1cfe3ee3e682
   
   
    //通知data去更新
    [self.barChartView.data notifyDataChanged];
    //通知图表去更新
    [self.barChartView notifyDataSetChanged];
}

#pragma mark ----- 创建曲线
-(BarChartDataSet*)createDataSetWithModel:(DeviceChartFieldModel*)model linecolor:(NSString*)colorStr;
{
    NSMutableArray *entryArr = [[NSMutableArray alloc]init];
    
    [self.chartModel.xTitlesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BarChartDataEntry *entry = [[BarChartDataEntry alloc] initWithX:idx y:[model.dataArray[idx] floatValue]];
        [entryArr addObject:entry];
    }];
    

    BarChartDataSet *set = [[BarChartDataSet alloc] initWithEntries:entryArr label:model.keyName];
    //是否在柱形图上面显示数值
    set.drawValuesEnabled = NO;
    set.valueFormatter = self;
    [set setColor:kCOLOR_HEX(colorStr)];//折线颜色
    set.highlightEnabled = YES;

    return set;
}

- (void)setupUI{
    [self setBackgroundColor:UIColor.whiteColor];
    UIView *itemBgView = [[UIView alloc] init];
    [itemBgView setBackgroundColor:UIColor.whiteColor];
    [self addSubview:itemBgView];
    //只有日曲线的话隐藏掉
    itemBgView.hidden = YES == (self.type == 2);
    
    
    kWeakSelf;
    UIView *line = kView;
    line.backgroundColor = CMainColorGreen;
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.offset(2);
    }];
    line.hidden = YES;
    
    
    NSArray *titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    if (self.type == 0) {
        titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    }else if (self.type == 1){
        titles = @[@"日".rh_localized,@"月".rh_localized];
    }else if (self.type == 2){
        titles = @[@"日".rh_localized];
    }
    __block QMUIButton *lastbtn;
   
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:_nameStr];
        //CGSize size = [self.nameLab getLableSizeWithAttStr:attr maxHeight:18];
        QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundColor:UIColor.whiteColor];
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        btn.layer.cornerRadius = 5;
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor = kCOLOR_HEX(@"#E3E6ED").CGColor;
        btn.layer.borderWidth = 1;
        CGFloat width = [obj getStringWidthFont:btn.titleLabel.font limitHeight:200];
        [itemBgView addSubview:btn];
        
        if(idx == 0){
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(btn.mas_bottom).offset(0);
                    make.centerX.equalTo(btn);
                    make.width.equalTo(btn).offset(-10);
            }];
        }
        
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf btnAction:idx];
            [line mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(x.mas_bottom).offset(0);
                    make.centerX.equalTo(x);
                    make.width.equalTo(x).offset(-10);
                    make.height.offset(2);
            }];
            
        }];
        
        
        [RACObserve(weakSelf, selectIndex) subscribeNext:^(id  _Nullable x) {
            NSInteger index = [x integerValue];
            NSLog(@"--->index:%ld  button:%@",index,btn);
            if (index == idx) {
                [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"ffffff") forState:UIControlStateNormal];
                btn.backgroundColor = CMainColorGreen;
                btn.layer.borderColor = CMainColorGreen.CGColor;
              
            }else{
                [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"969799") forState:UIControlStateNormal];
                btn.backgroundColor = UIColor.whiteColor;
                btn.layer.borderColor = kCOLOR_HEX(@"#E3E6ED").CGColor;
               
            }
            
        }];
        
        if (!lastbtn) {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0.5);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }else{
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastbtn.mas_right).offset(2);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }
        lastbtn = btn;
    }];
    
    [lastbtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-0.5);
    }];
    
    [itemBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
    }];
    
    //全屏
    QMUIButton *full_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [full_btn setImagePosition:QMUIButtonImagePositionRight];
    [full_btn setImage:[UIImage imageNamed:self.isLandscape?@"full_back":@"kwt_full_screen"] forState:UIControlStateNormal];
    [full_btn setTitle:@"" forState:UIControlStateNormal];
    [self addSubview:full_btn];
    
    //时间
    QMUIButton *dateBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [dateBtn setBackgroundColor:UIColor.whiteColor];
    [dateBtn setTitle:@"2023-08-09" forState:UIControlStateNormal];
    [dateBtn setImagePosition:QMUIButtonImagePositionRight];
    dateBtn.spacingBetweenImageAndTitle = 5;
    [dateBtn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
    [dateBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:dateBtn];
    self.timeBtn = dateBtn;
    
    //上一天
    _l_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_l_btn setImagePosition:QMUIButtonImagePositionRight];
    [_l_btn setImage:[UIImage imageNamed:@"day_left"] forState:UIControlStateNormal];
    [self addSubview:_l_btn];
    
    //下一天
    _r_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_r_btn setImagePosition:QMUIButtonImagePositionRight];
    [_r_btn setImage:[UIImage imageNamed:@"day_right"] forState:UIControlStateNormal];
    [self addSubview:_r_btn];

    [self addSubview:self.barChartView];
    
    //添加单位
    QMUILabel *leftUnitLab = [[QMUILabel alloc]init];
    leftUnitLab.textColor = UIColor.lightGrayColor;
    leftUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:leftUnitLab];
    self.leftUnitLab = leftUnitLab;
    
    QMUILabel *rightUnitLab = [[QMUILabel alloc]init];
    rightUnitLab.textColor = UIColor.lightGrayColor;
    rightUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:rightUnitLab];
    self.rightUnitLab = rightUnitLab;
    
    [leftUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(8);
        make.top.equalTo(dateBtn.mas_bottom).offset(weakSelf.type == 2?5:0);
        make.height.greaterThanOrEqualTo(@(18));
    }];
    
    [rightUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-8);
        make.centerY.equalTo(leftUnitLab);
    }];
    
    //下面的曲线标签按钮
    _scrollBgView = [[UIView alloc] init];
    [_scrollBgView setBackgroundColor:UIColor.whiteColor];
    [self addSubview:_scrollBgView];
    
    
    __block DeviceChartItemView *lastItem;
    __block CGFloat width = 5;
    [self.colorList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartItemView *itemView = [[DeviceChartItemView alloc] init];
        [itemView.markLab.layer setBorderColor:FontColor(obj).CGColor];
//        [itemView shadow:UIColor.blackColor opacity:0.1 radius:5 offset:CGSizeMake(0, 1)];
        [_scrollBgView addSubview:itemView];
        [self.itemsArray addObject:itemView];

        if (!lastItem) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(width);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width;
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastItem.mas_right).offset(5);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width+5;
        }
        lastItem = itemView;
    }];
    
    [lastItem mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(0);
    }];
    
    
    [self.scrollBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.barChartView.mas_bottom).offset(5);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    
    
    [full_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 40));
        make.right.mas_offset(0);
        make.centerY.equalTo(lastbtn);
    }];
    
    //只有日曲线的情况
    if (self.type == 2) {
        [dateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(full_btn);
            make.size.mas_equalTo(CGSizeMake(80, 30));
            make.centerX.mas_offset(0);
        }];
    }else{
        [dateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(full_btn.mas_bottom).offset(2);
            make.size.mas_equalTo(CGSizeMake(80, 30));
            make.centerX.mas_offset(0);
        }];
    }
   
    
    [_l_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.right.equalTo(dateBtn.mas_left);
    }];

    [_r_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.left.equalTo(dateBtn.mas_right);
    }];
    
    [self.barChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.leftUnitLab.mas_bottom).offset(10);
        //横屏不限定高度
        if (!weakSelf.isLandscape) {
            make.height.offset(200);
        }
       
    }];
   
    
    [[full_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf fullAction];
    }];
    
    [[_l_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往前
        if (weakSelf.subTimeBlock) {
            weakSelf.subTimeBlock();
        }
    }];
    
    [[_r_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往后
        if (weakSelf.addTimeBlock) {
            weakSelf.addTimeBlock();
        }
    }];
    
    [[dateBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (weakSelf.changeTimeBlock) {
            weakSelf.changeTimeBlock();
        }
    }];
}


- (void)fullAction{
    if (self.fullChartBlock) {
        self.fullChartBlock();
    }
}

- (void)btnAction:(NSInteger)index{
    [self.barChartView clear];
    if (self.selectTopToolBlock) {
        self.selectTopToolBlock(index);
    }
    
    if (index == -1) {//自定义参数设置
        return;
    }
    
    self.selectIndex = index;
  
    if (self.selectIndex == 1) {//Day
        
    }
    
    if (self.selectIndex == 2) {//Month
        
    }
    
    if (self.selectIndex == 3) {//Year
        
    }
    
    if (self.selectIndex == 4) {//Total
        
    }
}



-(BarChartView *)barChartView
{
    if (!_barChartView) {
        _barChartView = [[BarChartView alloc] init];
        _barChartView.backgroundColor = [UIColor whiteColor];
        _barChartView.noDataText = @"没有数据";
        _barChartView.frame = CGRectMake(0, 0, 300, 200);
        _barChartView.dragEnabled = NO;
        _barChartView.pinchZoomEnabled = NO;   //捏合手势
        _barChartView.doubleTapToZoomEnabled = NO; //双击手势
        
        _barChartView.legend.enabled = YES;
        _barChartView.chartDescription.enabled = YES;
        _barChartView.extraTopOffset = 5;//图表边距
        _barChartView.extraLeftOffset = 5;
        _barChartView.extraRightOffset = 20;
        _barChartView.extraBottomOffset = 0;
        
        _barChartView.legend.enabled = NO;//是否显示说明图标
        _barChartView.legend.form = ChartLegendFormSquare;//说明图例的样式  --指导价走势
        _barChartView.legend.formSize = 8;//图例大小（头部）
        _barChartView.legend.formToTextSpace = 5;//图例与文字的距离
        _barChartView.legend.yOffset = 0;//图例与底部的距离
        _barChartView.legend.xOffset = 0;//图例与左边的距离
        _barChartView.legend.xEntrySpace = 50;//图例与图例之间的距离
        _barChartView.legend.stackSpace = 20;
       
        
        //气泡标签
        _barChartView.drawMarkers = YES;
        self.markerView = [[RHBarChartMarkerView alloc]init];
        _barChartView.marker = self.markerView;
        self.markerView.chartView = _barChartView;
        
        //X 轴
        ChartXAxis *xAxis = _barChartView.xAxis;
        xAxis.labelPosition = XAxisLabelPositionBottom;
        xAxis.labelFont = [UIFont systemFontOfSize:10.f];
//        xAxis.labelWidth = 10;
        xAxis.gridLineDashPhase = 0.f;
        //不绘制网格线
        xAxis.drawGridLinesEnabled = NO;
//        xAxis.axisMinimum = -0.5;
        xAxis.labelRotationAngle = 0;
        //设置虚线样式的网格线
        xAxis.gridLineDashLengths = @[@0.f, @0.f];
        //x轴标签间隔尺寸
    //        xAxis.granularity = 1;
        //设置label间隔，若设置为1，每个柱形下面都会显示label
//        xAxis.spaceMin = 1;
        xAxis.valueFormatter = self;
        
        //Y轴
        _barChartView.rightAxis.enabled = NO;//不绘制右边轴
        ChartYAxis *leftAxis = _barChartView.leftAxis;
    //        leftAxis.axisMaximum = 100.0;
        leftAxis.labelFont = [UIFont systemFontOfSize:12];
        leftAxis.labelTextColor = UIColor.lightGrayColor; //文本颜色
        leftAxis.axisMinimum = 0.0;
        leftAxis.axisLineWidth = 0;
        //设置虚线样式的网格线
        [leftAxis setLabelCount:6 force:YES];
        leftAxis.gridLineDashLengths = @[@3.f, @3.f];
        leftAxis.valueFormatter = self;
        [self addSubview:_barChartView];
    }
    return _barChartView;
}

#pragma mark --------------------chartView delegate ------------------

#pragma mark - 折线值
- (NSString *)stringForValue:(double)value entry:(ChartDataEntry *)entry dataSetIndex:(NSInteger)dataSetIndex viewPortHandler:(ChartViewPortHandler *)viewPortHandler {
    
    return [NSString stringWithFormat:@"%.0f", value];
}
 
#pragma mark - x,y轴值
- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis {
   
    if ([axis isEqual:self.barChartView.xAxis]) {
        NSNumber *num = [NSNumber numberWithDouble:fabs(value)];
        return [self.chartModel.xTitlesArray safeObjectAtIndex:[num integerValue]];
    }
    return [NSDecimalNumber decimalPlacesWithRoundUpWithDigit:1 value:value];

}


#pragma mark 图表中数值被选中
-(void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight{
    
//    [self.maskView updateModel:self.chartModel index:(NSInteger)highlight.x colors:self.colorList];
//
//    ChartMarkerView *makerView = (ChartMarkerView*)chartView.marker;
//    CGFloat off_x = 0;
//    if(chartView.width - highlight.xPx < self.maskView.width)
//    {
//        off_x = -self.maskView.width;
//    }else if (highlight.xPx < self.maskView.width/2){
//        off_x = 0;
//    }else{
//        off_x = -self.maskView.width/2;
//    }
//
//    CGFloat off_y = 0;
//    if(chartView.height - highlight.yPx < self.maskView.height)
//    {
//        off_y = -self.maskView.height;
//    }else if (highlight.yPx < self.maskView.height/2){
//        off_y = 0;
//    }else{
//        off_y = -self.maskView.height/2;
//    }
//
//
//    makerView.offset = CGPointMake(off_x, off_y);
//
//
    
    
}

#pragma mark 图表中的空白区域被选中
-(void)chartValueNothingSelected:(ChartViewBase *)chartView{
    NSLog(@"空白区域被选中");
}

#pragma mark 图表被缩放
-(void)chartScaled:(ChartViewBase *)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
//    NSLog(@"图表被缩放");
    //根据缩放调整显示间隔
//    if(scaleX>=3){
//        self.lineChartView.xAxis.granularity = 1;
//    }else if(scaleX>=2){
//        self.lineChartView.xAxis.granularity = 2;
//    }
//    chartView.xAxis.granularity = self.chartModel.xTitlesArray.count/8*scaleX;
//    NSLog(@"------>图表缩放倍数:%f",scaleX);
    
//    NSString *time = @"23:23";
//    CGFloat width = [time getStringWidthFont:self.lineChartView.xAxis.labelFont limitHeight:25];
//    NSLog(@"----->333%@",chartView.xAxis.yy_modelDescription);
//  self.lineChartView.xAxis.granularity =  chartView.xAxis.entries.count/6;
    
}

#pragma mark 图表被移动
-(void)chartTranslated:(ChartViewBase *)chartView dX:(CGFloat)dX dY:(CGFloat)dY{
//    NSLog(@"图表被移动");
}


#pragma mark ------ lazy load

- (NSMutableArray *)itemsArray{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}

-(NSMutableArray *)unitArr
{
    if(!_unitArr)
    {
        _unitArr = [NSMutableArray array];
    }
    return _unitArr;;
}

-(void)dealloc
{
    
}
@end
